package com.jiang.annotation.valid.test;

import com.jiang.annotation.valid.group.Group1;
import com.jiang.annotation.valid.group.Group2;
import com.jiang.annotation.valid.test.service.ValidServiceA;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;

@RestController
@RequestMapping("/valid")
@Validated
public class ValidController {

    @Autowired
    ValidServiceA validServiceA;

    /**
     * 单个参数校验(注：需要使用@Validated开启校验，也只有这里需要用到)，并且会对每个参数都进行校验
     * @param age
     * @return
     */
    // http://localhost:8080/valid/getAge?age=6&salary=10001
    @RequestMapping("/getAge")
    public String getAge(@Range(min = 18,max = 100) int age, @Max(value = 10000, message = "必须小于或等于10000") int salary) {
        return "ok";
    }

    /**
     * 实体类校验
     * @param user
     * @return
     */
    // http://localhost:8080/valid/getUser?userId=1&name=@小红&sex=女&birthday=2022-07-11&address=武汉市
    @RequestMapping("/getUser")
    public User getUser(@Valid User user) {
        return user;
    }
    @PostMapping("/getUserPost")
    public User getUserPost(@RequestBody @Valid User user) {
        return user;
    }

    /**
     * Controller层调用service时在service层校验
     * @param user
     * @return
     */
    // http://localhost:8080/valid/printName?name=张三22&address=61616516546516165161
    @RequestMapping("/printName")
    public void printName(User user) {
        validServiceA.print(user.getName(), user.getAddress());
    }
    // http://localhost:8080/valid/saveUser1?userId=1&name=@小明&sex=男1&birthday=2022-07-11&address=武汉&grade=4&graduateAge=22
    @RequestMapping("/saveUser1")
    public boolean saveUser1(User user) {
        return validServiceA.saveUserA(user);
    }

    /**
     * serviceA调用serviceB时在serviceB层校验
     * @param user
     * @return
     */
    // http://localhost:8080/valid/saveUser2?userId=1&name=@小明&sex=男1&birthday=2022-07-11&address=武汉
    @RequestMapping("/saveUser2")
    public boolean saveUser2(User user) {
        return validServiceA.saveUserAToB(user);
    }

    /**
     * 分组校验
     * 如果只有@Validated({Group...})时，只对User字段的校验注解上带有对应Group的进行校验，其他字段不校验
     * `@Validated({Group...})+@Valid一起使用时，除了上述校验规则外，其他字段的校验不影响
     * @param user
     * @return
     */
    // http://localhost:8080/valid/saveUser3?userId=1&name=@小明&sex=男1&birthday=2022-07-11&address=武汉&grade=4&graduateAge=22
    @RequestMapping("/saveUser3")
    public boolean saveUser3(@Validated({Group1.class}) User user) {
//        return true;  //只有@Validated分组校验
        return validServiceA.saveUserA(user);   //@Validated分组校验和@Valid校验共同作用
    }
}
